#include "indexfile.h"

IndexFile::IndexFile(QObject *parent) : QObject(parent)
{
    IndexContainer.clear();
}

IndexFile::~IndexFile()
{
    IndexContainer.clear();
}


void IndexFile::SetFileName(QString name)
{
    FileName = name;
    ReadIndexFile();
}

void IndexFile::ReadIndexFile()
{
    QFile file(FileName);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    QTextStream in(&file);
    while(!in.atEnd()) {
        IndexContainer.push_back(in.readLine());
    }
    file.close();
}

void IndexFile::SetString(QString Section, QString Item, QString Value)
{
    AddIndextoContainer(Section, Item, Value);
}

void IndexFile::SetFloat(QString Section, QString Item, float Value)
{
    AddIndextoContainer(Section, Item, QString::number(Value));
}

void IndexFile::SetInt(QString Section, QString Item, int Value)
{
    AddIndextoContainer(Section, Item, QString::number(Value));
}

void IndexFile::AddIndextoContainer(QString Section, QString Item, QString Value)
{
    QString TmpData;
    if(IndexContainer.size() > 0) {
        // 找到头结点
        for(int i = 0; i < IndexContainer.size(); i++) {
            TmpData = IndexContainer.at(i);
            if(TmpData.contains(Section)) {
                // 找到数据结点修改其数据值
                for(int j = i + 1; j < IndexContainer.size(); j++) {
                    TmpData = IndexContainer.at(j);
                    if(TmpData.contains(Item)) {
                        QString data = TmpData.left(TmpData.indexOf('=') + 1);
                        data = data + " " + Value;
                        IndexContainer.push_back(data);
                        return;
                    }
                    else {
                        continue;
                    }
                }
                // 没有找到则在后面插入一个数据节点及其数据
                IndexContainer.insert(i + 1, "  " + Item + " = " + Value);
                return;
            }
            else {
                continue;
            }
        }
        // 没有找到头结点直接在最后插入数据
        IndexContainer.push_back("[" + Section + "]");
        IndexContainer.push_back("  " + Item + " = " + Value);
    }
    else {
        IndexContainer.push_back("[" + Section + "]");
        IndexContainer.push_back("  " + Item + " = " + Value);
    }
}

void IndexFile::WriteIndexFile()
{
    QString data;
    QFile file(FileName);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;
    for(int i = 0; i < IndexContainer.size(); i++) {
        data = IndexContainer.at(i);
        data += "\r\n";
        file.write(data.toStdString().c_str());
    }
    file.close();
}
